package com.neusoft.neuiotms.dcam.workflow.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javax.persistence.EntityNotFoundException;
import javax.transaction.Transactional;

import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.neusoft.bizcore.activiti.dto.ProcessInstanceDTO;
import com.neusoft.bizcore.activiti.service.ProcessInstanceService;
import com.neusoft.bizcore.activiti.service.WorkOrderService;
import com.neusoft.bizcore.auth.common.bean.UserBean;
import com.neusoft.bizcore.web.constant.ExceptionConstants;
import com.neusoft.bizcore.web.exception.UnitedException;
import com.neusoft.neuiotms.dcam.anhui.itsm.WorkflowBean;
import com.neusoft.neuiotms.dcam.constant.DCAMConsts;
import com.neusoft.neuiotms.dcam.fixed.dto.AssetLifeCycleDTO;
import com.neusoft.neuiotms.dcam.fixed.model.Asset;
import com.neusoft.neuiotms.dcam.fixed.repository.AssetRepository;
import com.neusoft.neuiotms.dcam.fixed.service.AssetLifeCycleService;
import com.neusoft.neuiotms.dcam.fixed.service.AssetService;
import com.neusoft.neuiotms.dcam.fixed.service.ItsmService;
import com.neusoft.neuiotms.dcam.workflow.converter.BaofeiKJConverter;
import com.neusoft.neuiotms.dcam.workflow.converter.ITSMApproveConverter;
import com.neusoft.neuiotms.dcam.workflow.dto.BaofeiItemKJDTO;
import com.neusoft.neuiotms.dcam.workflow.dto.BaofeiKJDTO;
import com.neusoft.neuiotms.dcam.workflow.dto.ITSMApproveDTO;
import com.neusoft.neuiotms.dcam.workflow.model.BaofeiItemKJ;
import com.neusoft.neuiotms.dcam.workflow.model.BaofeiKJ;
import com.neusoft.neuiotms.dcam.workflow.model.ITSMApprove;
import com.neusoft.neuiotms.dcam.workflow.repository.BaofeiItemKJRepository;
import com.neusoft.neuiotms.dcam.workflow.repository.BaofeiKJRepository;
import com.neusoft.neuiotms.dcam.workflow.repository.ITSMApproveRepository;
import com.neusoft.neuiotms.dcam.workflow.service.BaofeiKJService;

import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class BaofeiKJServiceImpl implements BaofeiKJService {

    @Autowired
    private WorkOrderService workOrderService;
    @Autowired
    private ProcessInstanceService processInstanceService;
    @Autowired
    private BaofeiKJRepository baofeiKJRepository;
    @Autowired
    private BaofeiKJConverter baofeiKJConverter;
    @Autowired
    private ITSMApproveRepository approveRepository;
    @Autowired
    private ITSMApproveConverter approveConverter;
    @Autowired
    private BaofeiItemKJRepository baofeiItemKJRepository;
    @Autowired
    private AssetRepository assetRepository;
    @Autowired
    private AssetService assetService;
    @Autowired
    private AssetLifeCycleService assetLifeCycleService;
    @Autowired
    private ItsmService itsmService;

    @Override
    @Transactional
    public BaofeiKJDTO create(final BaofeiKJDTO dto, final UserBean user) {

        final String taskId = dto.getTaskId();
        final ProcessInstanceDTO instance =
                this.workOrderService.submit(dto.getTitle(), DCAMConsts.PROCESSS_BAOFEI_KJ_KEY, dto.getWorkOrderNum(),
                        user);
        dto.setTaskId(instance.getTaskId());
        dto.setWorkOrderNum(instance.getWorkorderNum());
        dto.setCreateUser(user.getUsername());
        dto.setCreateUserName(user.getName());

        // 查询当前workOrderNum和TaskId下是否存在记录
        final BaofeiKJ oldModel = this.baofeiKJRepository.findByWorkOrderNumAndTaskId(
                dto.getWorkOrderNum(), taskId);
        if (oldModel == null) {
            dto.setId(null);
        }

        // 解锁以前的资产信息
        final List<BaofeiItemKJ> all = this.baofeiItemKJRepository.findByMain_WorkOrderNum(dto.getWorkOrderNum());
        if (null != all) {
            this.assetService.updateLocked(all.stream().map(l -> l.getCode()).distinct().collect(Collectors.toList()),
                    false);
        }

        BaofeiKJ model = this.baofeiKJConverter.toModel(dto);
        model = this.baofeiKJRepository.save(model);

        // 枷锁资产信息
        this.assetService.updateLocked(
                model.getDetails().stream().map(l -> l.getCode()).distinct().collect(Collectors.toList()),
                true);

        // 完成当前节点
        this.processInstanceService.complete(dto.getWorkOrderNum(), dto.getTaskId(), user);
        try {
            // 对接ITSM
            final List<WorkflowBean.AssetBean> assetList = Lists.newArrayList();
            for (final BaofeiItemKJDTO item : dto.getDetails()) {
                final WorkflowBean.AssetBean assetBean = WorkflowBean.AssetBean.builder()
                        .assetId(item.getCode())
                        .assetClassID(item.getSmallTypeCode())
                        .assetModel(item.getSpecifications())
                        .assetUnit("未知")
                        .assetPrice(0)
                        .assetNumber(1)
                        .assetName(item.getName())
                        .assetType("1")
                        .assetSign("未知")
                        .build();
                assetList.add(assetBean);
            }

            final WorkflowBean workflowBean = WorkflowBean.builder()
                    .workNum(dto.getWorkOrderNum())
                    .workName("设备报废")
                    .workType("60")
                    .workContent("设备报废申请")
                    .applyUser(user.getUsername())
                    .assetList(assetList)
                    .build();

            this.itsmService.pushItsm(workflowBean);
        } catch (final Exception e) {
            BaofeiKJServiceImpl.log.error("设备报废流程推送ITSM时发生错误", e);
        }

        return this.baofeiKJConverter.toDTO(model);
    }

    @Override
    public BaofeiKJDTO detail(final String workOrderNum, final String taskId, final UserBean user) {
        BaofeiKJ model = null;
        try {
            if (StringUtils.isNotBlank(workOrderNum) && !"NULL".equals(taskId)) {
                model = this.baofeiKJRepository.findByWorkOrderNumAndTaskId(workOrderNum, taskId);
                if (model == null) {
                    // 获取前一节点的TaskID
                    final String lastTaskId = this.processInstanceService.getLastTaskId(taskId, user);
                    if (lastTaskId == null) {
                        return new BaofeiKJDTO();
                    } else {
                        model = this.baofeiKJRepository.findByWorkOrderNumAndTaskId(workOrderNum,
                                lastTaskId);
                    }
                }
            } else if ("NULL".equals(taskId)) {
                final List<BaofeiKJ> BaofeiKJs =
                        this.baofeiKJRepository.findAllByWorkOrderNumOrderByCreateTimeDesc(workOrderNum);
                if ((BaofeiKJs != null) && (BaofeiKJs.size() > 0)) {
                    model = BaofeiKJs.get(0);
                }
            }
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND,
                    new Object[] {workOrderNum },
                    new Object[] {taskId });
        }
        return this.baofeiKJConverter.toDTO(model);
    }

    @Override
    @Transactional
    public ITSMApproveDTO itsmCreate(final ITSMApproveDTO dto, final UserBean user) {
        final ITSMApprove model = this.approveConverter.toModel(dto);
        this.approveRepository.save(model);

        this.processInstanceService.setGlobalVariable(dto.getTaskId(), DCAMConsts.PROCESSS_BAOFEI_KJ_APPROVE_RESULT,
                dto.getResult());
        // 完成当前节点
        this.processInstanceService.complete(dto.getWorkOrderNum(), dto.getTaskId(), user);

        // 如果审批同意的情况下创建资产信息
        if ("1".equals(dto.getResult())) {
            // 更新资产状态为待报废
            final List<BaofeiKJ> models =
                    this.baofeiKJRepository.findAllByWorkOrderNumOrderByCreateTimeDesc(dto.getWorkOrderNum());
            if ((models != null) && (models.size() > 0)) {
                final List<String> codes = models.get(0).getDetails().stream().map(l -> l.getCode()).distinct()
                        .collect(Collectors.toList());
                this.baofeiKJCompleteUpdate(codes, dto.getWorkOrderNum());
            }
        }

        return this.approveConverter.toDTO(model);
    }

    @Override
    public ITSMApproveDTO itsmDetails(final String workOrderNum, final String taskId, final UserBean user) {
        ITSMApprove model = null;
        try {
            if (StringUtils.isNotBlank(workOrderNum) && !"NULL".equals(taskId)) {
                model = this.approveRepository.findByWorkOrderNumAndTaskId(workOrderNum, taskId);
                if (model == null) {
                    // 获取前一节点的TaskID
                    final String lastTaskId = this.processInstanceService.getLastTaskId(taskId, user);
                    if (lastTaskId == null) {
                        return new ITSMApproveDTO();
                    } else {
                        model = this.approveRepository.findByWorkOrderNumAndTaskId(workOrderNum,
                                lastTaskId);
                    }
                }
            } else if ("NULL".equals(taskId)) {
                final List<ITSMApprove> baofeiKJs =
                        this.approveRepository.findAllByWorkOrderNumOrderByCreateTimeDesc(workOrderNum);
                if ((baofeiKJs != null) && (baofeiKJs.size() > 0)) {
                    model = baofeiKJs.get(0);
                }
            }
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND,
                    new Object[] {workOrderNum },
                    new Object[] {taskId });
        }
        return this.approveConverter.toDTO(model);
    }

    private void baofeiKJCompleteUpdate(final List<String> codes, final String workOrderNum) {

        final List<AssetLifeCycleDTO> lifeList = new ArrayList<>();

        if ((codes != null) && (codes.size() > 0)) {
            final List<Asset> assets = this.assetRepository.findByCodeIn(codes);
            if (null != assets) {
                assets.forEach(l -> {
                    l.setLocked(false);
                    l.setStatus(DCAMConsts.ASSET_STATUS_TOSCRAP);

                    // 生命周期
                    lifeList.add(AssetLifeCycleDTO.builder().code(l.getCode())
                            .lifeCycle(DCAMConsts.ASSET_LIFE_TYPE_BAOFEI)
                            .content(l.getName() + "准备报废").workNum(workOrderNum).build());
                });
                this.assetRepository.saveAll(assets);

                if (lifeList.size() > 0) {
                    this.assetLifeCycleService.batchCreate(lifeList);
                }
            }
        }
    }

}
